/* timer.c - initializes pit and handles the clock */

#include	"timer.h"
#include	"isr.h"
#include	"monitor.h"
#include	"task.h"
#include	"kheap.h"

u32int tick = 0;
extern struct task *current_task;
extern struct task *ready_queue;
extern struct task *sched_task;
extern u8int flag_task;

u8int sched_reentry = 0;

static void timer_callback(struct registers regs){
	
	tick++;

	if(!current_task || !flag_task){
		return;
	}
/*
	if(current_task -> id == 0){
		task_switch(1);
		return;
	}
*/
	if(current_task -> quantum){
		(current_task -> quantum)--;
	}else{

		monitor_write("\n[timer] rescheduling task ");
		monitor_write_hex(current_task -> id);
		monitor_write("\n\n");

		current_task -> quantum = DEFAULT_QUANTA;
		sched_reentry = 1;
/*
		sched_task = current_task;
*/
		/* seperate current_task */
	/*
		current_task = (struct task *)kmalloc(sizeof(struct task));
		*current_task = *ready_queue; 
	*/	
		task_switch(0);
	}
}

void init_timer(u32int freq){
	u32int divisor = 1193180 / freq;
	u8int lo, hi;

	monitor_write("Initializing timer.\n");
	
	reg_intrh(IRQ0, &timer_callback);

	outb(0x43, 0x36);

	lo = (u8int) (divisor & 0xFF);
	hi = (u8int) ((divisor >> 8) & 0xFF);

	outb(0x40, lo);
	outb(0x40, hi);
}
